//
//  MessageViewController.m
//  KiklinkApp
//
//  Created by LJC on 14-9-15.
//  Copyright (c) 2014年 Kiklink. All rights reserved.
//

#import "MessageViewController.h"

#import "ImagesManager.h"
#import "UIColor+hex.h"
#import "UIView+loadWithNib.h"

#import "MJRefresh.h"
#import "MessageCell.h"

#import "API.h"

NSString *const messageTableCellIdentifier1 = @"MessageCell";
NSString *const messageTableCellIdentifier2 = @"MessageCell";

@interface MessageViewController ()
{
    //data
    NSMutableArray *messageTableArray1;
    NSMutableArray *messageTableArray2;
    NSInteger page1;
    NSInteger page2;
    NSInteger totalPage1;
    NSInteger totalPage2;
}
@end

@implementation MessageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"我的消息";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    
    
    //loading
    [self.activity1 startAnimating];
    [self.activity2 startAnimating];
    self.refreshBtn1.hidden = YES;
    self.refreshBtn2.hidden = YES;
    [self.refreshBtn1 addTarget:self action:@selector(refresh1) forControlEvents:UIControlEventTouchUpInside];
    [self.refreshBtn2 addTarget:self action:@selector(refresh2) forControlEvents:UIControlEventTouchUpInside];
    
    
    //BundleImages
    ImagesManager *imagesManager = [ImagesManager sharedImagesManager];
    
    
    //leftNavItem
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backButton setFrame:CGRectMake(0, 0, NavBarHeight/4, NavBarHeight/2)];
    [backButton setBackgroundImage:[imagesManager back] forState:UIControlStateNormal];
    [backButton setBackgroundImage:[imagesManager backTapped] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftNavBarItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftNavBarItem;

    
    //segment
    self.segment.tintColor = [UIColor colorWithHexString:AppColor_Main];
    [self.segment addTarget:self action:@selector(segmentAction) forControlEvents:UIControlEventValueChanged];
    
    
    //messageTable
    self.messageTable1.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.messageTable1.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.messageTable1.delegate = self;
    self.messageTable1.dataSource = self;
    [self.messageTable1 registerClass:[UITableViewCell class] forCellReuseIdentifier:messageTableCellIdentifier1];
    
    self.messageTable2.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.messageTable2.backgroundColor = [UIColor colorWithHexString:AppColor_BackGround];
    self.messageTable2.delegate = self;
    self.messageTable2.dataSource = self;
    [self.messageTable2 registerClass:[UITableViewCell class] forCellReuseIdentifier:messageTableCellIdentifier2];
    
    [self setupRefresh];
    
    
    //data
    messageTableArray1 = [[NSMutableArray alloc] init];
    messageTableArray2 = [[NSMutableArray alloc] init];
    page1 = 1;
    page2 = 1;
    [self getData:1 Condition:@"first" Style:@"unRead"];
    [self getData:1 Condition:@"first" Style:@"all"];
}

#pragma mark - get data
//condition:first&header&footer  style:unRead&all
- (void)getData:(NSInteger)pageNum Condition:(NSString *)condition Style:(NSString *)style
{
    NSLog(@"page:%ld",(long)pageNum);
    if ([style isEqualToString:@"unRead"]) {
        
        [API userMessageWithPageNumber:[NSNumber numberWithInteger:pageNum] callback:^(int stateCode, NSString *word, id content) {
            
            if (stateCode == SUCCESS) {
                
                MessagePage* messagePage = (MessagePage *)content;
                NSMutableArray *result = [[NSMutableArray alloc] initWithArray:messagePage.result];
                
                if ([condition isEqualToString:@"first"]) {
                    totalPage1 = messagePage.lastPageNumber;
                    self.messageTable1.scrollEnabled = YES;
                    page1 = 2;
                    messageTableArray1 = result;
                } else if ([condition isEqualToString:@"header"]) {
                    page1 = 2;
                    messageTableArray1 = result;
                } else if ([condition isEqualToString:@"footer"]) {
                    page1 ++;
                    [messageTableArray1 addObjectsFromArray:result];
                }
                
                [self loadData1:condition];
                
            } else {
                
                if ([condition isEqualToString:@"first"]) {
                    self.messageTable1.scrollEnabled = NO;
                    [self.activity1 stopAnimating];
                    self.refreshBtn1.hidden = NO;
                } else if ([condition isEqualToString:@"header"]) {
                    [self.messageTable1 headerEndRefreshing];
                } else if ([condition isEqualToString:@"footer"]) {
                    [self.messageTable1 footerEndRefreshing];
                }
                
            }
            
        }];
        
    } else if ([style isEqualToString:@"all"]) {
        
        [API systemMessageWithPageNumber:[NSNumber numberWithInteger:pageNum] callback:^(int stateCode, NSString *word, id content) {
            
            if (stateCode == SUCCESS) {
                
                MessagePage* messagePage = (MessagePage *)content;
                NSMutableArray *result = [[NSMutableArray alloc] initWithArray:messagePage.result];
                
                if ([condition isEqualToString:@"first"]) {
                    totalPage2 = messagePage.lastPageNumber;
                    self.messageTable2.scrollEnabled = YES;
                    page2 = 2;
                    messageTableArray2 = result;
                } else if ([condition isEqualToString:@"header"]) {
                    page2 = 2;
                    messageTableArray2 = result;
                } else if ([condition isEqualToString:@"footer"]) {
                    page2 ++;
                    [messageTableArray2 addObjectsFromArray:result];
                }
                
                [self loadData2:condition];
                
            } else {
                
                if ([condition isEqualToString:@"first"]) {
                    self.messageTable2.scrollEnabled = NO;
                    [self.activity2 stopAnimating];
                    self.refreshBtn2.hidden = NO;
                } else if ([condition isEqualToString:@"header"]) {
                    [self.messageTable2 headerEndRefreshing];
                } else if ([condition isEqualToString:@"footer"]) {
                    [self.messageTable2 footerEndRefreshing];
                }
                
            }
            
        }];
        
    }
    
}

- (void)loadData1:(NSString *)condition
{
    [self.messageTable1 reloadData];
    
    if ([condition isEqualToString:@"first"]) {
        [self.activity1 stopAnimating];
    } else if ([condition isEqualToString:@"header"]) {
        [self.messageTable1 headerEndRefreshing];
    } else if ([condition isEqualToString:@"footer"]) {
        [self.messageTable1 footerEndRefreshing];
    }
}
- (void)loadData2:(NSString *)condition
{
    [self.messageTable2 reloadData];
    
    if ([condition isEqualToString:@"first"]) {
        [self.activity2 stopAnimating];
    } else if ([condition isEqualToString:@"header"]) {
        [self.messageTable2 headerEndRefreshing];
    } else if ([condition isEqualToString:@"footer"]) {
        [self.messageTable2 footerEndRefreshing];
    }
}

- (void)refresh1
{
    self.refreshBtn1.hidden = YES;
    [self.activity1 startAnimating];
    
    [self getData:1 Condition:@"first" Style:@"unRead"];
}
- (void)refresh2
{
    self.refreshBtn2.hidden = YES;
    [self.activity2 startAnimating];
    
    [self getData:1 Condition:@"first" Style:@"all"];
}
#pragma mark - get data End

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - back
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - back End

#pragma mark - segmentAction
- (void)segmentAction
{
    NSInteger selectedIndex = self.segment.selectedSegmentIndex;
    switch (selectedIndex) {
        case 0:
            [self.messageTable1 setHidden:NO];
            [self.messageTable2 setHidden:YES];
            
            [self.loadingView1 setHidden:NO];
            [self.loadingView2 setHidden:YES];
            break;
        case 1:
            [self.messageTable1 setHidden:YES];
            [self.messageTable2 setHidden:NO];
            
            [self.loadingView1 setHidden:YES];
            [self.loadingView2 setHidden:NO];
            break;
        default:
            break;
    }
}
#pragma mark - segmentAction End

#pragma tableView dataSource&delegate  &MJRefresh
- (void)setupRefresh
{
    [self.messageTable1 addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.messageTable1 addFooterWithTarget:self action:@selector(footerRereshing)];
    self.messageTable1.headerPullToRefreshText = @"下拉可以刷新";
    self.messageTable1.headerReleaseToRefreshText = @"松开马上刷新";
    self.messageTable1.headerRefreshingText = @"正在刷新...";
    self.messageTable1.footerPullToRefreshText = @"上拉加载更多";
    self.messageTable1.footerReleaseToRefreshText = @"松开马上加载";
    self.messageTable1.footerRefreshingText = @"正在加载...";
    
    
    [self.messageTable2 addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.messageTable2 addFooterWithTarget:self action:@selector(footerRereshing)];
    self.messageTable2.headerPullToRefreshText = @"下拉可以刷新";
    self.messageTable2.headerReleaseToRefreshText = @"松开马上刷新";
    self.messageTable2.headerRefreshingText = @"正在刷新...";
    self.messageTable2.footerPullToRefreshText = @"上拉加载更多";
    self.messageTable2.footerReleaseToRefreshText = @"松开马上加载";
    self.messageTable2.footerRefreshingText = @"正在加载...";
}
- (void)headerRereshing
{
    //data
    if (self.segment.selectedSegmentIndex == 0) {
        [self getData:1 Condition:@"header" Style:@"unRead"];
    } else if (self.segment.selectedSegmentIndex == 1) {
        [self getData:1 Condition:@"header" Style:@"all"];
    }
}
- (void)footerRereshing
{
    //data
    if (self.segment.selectedSegmentIndex == 0) {
        if (page1 <= totalPage1) {
            [self getData:page1 Condition:@"footer" Style:@"unRead"];
        } else {
            [self.messageTable1 footerEndRefreshing];
        }
    } else if (self.segment.selectedSegmentIndex == 1) {
        if (page2 <= totalPage2) {
            [self getData:page2 Condition:@"footer" Style:@"all"];
        } else {
            [self.messageTable2 footerEndRefreshing];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.messageTable1) {
        return messageTableArray1.count;
    } else if (tableView == self.messageTable2) {
        return messageTableArray2.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.messageTable1) {
        BOOL nibsRegistered = NO;
        if (!nibsRegistered) {
            UINib *nib = [UINib nibWithNibName:@"MessageCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:messageTableCellIdentifier1];
            nibsRegistered = YES;
        }
        MessageCell *cell = (MessageCell *)[tableView dequeueReusableCellWithIdentifier:messageTableCellIdentifier1];
        [cell loadDataWithMessage:[messageTableArray1 objectAtIndex:indexPath.row]];
        return cell;
    } else if (tableView == self.messageTable2) {
        BOOL nibsRegistered = NO;
        if (!nibsRegistered) {
            UINib *nib = [UINib nibWithNibName:@"MessageCell" bundle:nil];
            [tableView registerNib:nib forCellReuseIdentifier:messageTableCellIdentifier2];
            nibsRegistered = YES;
        }
        MessageCell *cell = (MessageCell *)[tableView dequeueReusableCellWithIdentifier:messageTableCellIdentifier2];
        [cell loadDataWithMessage:[messageTableArray2 objectAtIndex:indexPath.row]];
        return cell;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.messageTable1) {
        return [MessageCell cellHeight:[messageTableArray1 objectAtIndex:indexPath.row]];
    } else if (tableView == self.messageTable2) {
        return [MessageCell cellHeight:[messageTableArray2 objectAtIndex:indexPath.row]];
    }
    return 0;
}
#pragma tableView dataSource&delegate End

@end
